const path = require('path');
const { promisify } = require('util');
const open = require('open');
const download = promisify(require('download-git-repo'));
const { compileEjsFile, syncCreateDir, writeToFile } = require('../util/index');
const { commandSpawn } = require('../util/terminal');
const { VueRepo } = require('../config/index');

const createCommandAction = async (name) => {
  try {
    // 1.clone项目
    await download(VueRepo, name, { clone: true });
    // 2. npm 安装
    const npmCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
    await commandSpawn(npmCmd, ['install'], { cwd: `./${name}` });
    // 3.启动服务
    await commandSpawn(npmCmd, ['run', 'serve'], { cwd: `./${name}` });
    // 4. 打开浏览器
    await open('http://localhost:8080/');
  } catch (error) {
    console.log('error:', error);
  }
};

const createPageAction = async (pageName, dest) => {
  console.log('createPageAction:', pageName, dest);
  try {
    // 1.读模板文件
    const result = await compileEjsFile('page.ejs', pageName);
    // 2.写入文件
    if (syncCreateDir(dest)) {
      const pagePath = path.resolve(dest, `${pageName}.vue`);
      await writeToFile(pagePath, result);
    }
  } catch (error) {
    console.log(error);
  }
};

module.exports = {
  createCommandAction,
  createPageAction,
};
